# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# AmosERP odoo11.0
# QQ:35350428
# 邮件:35350428@qq.com
# 手机：13584935775
# 作者：'odoo'
# 公司网址： www.odoo.pw  www.100china.cn www.amoserp.com
# Copyright 昆山一百计算机有限公司 2012-2020 Amos
# 日期：2019/11/14
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import UserError, ValidationError
from ding_client import Client
from dingtalk import SecretClient, AppKeyClient
import time, datetime
from jinja2 import Template

class hr_department(models.Model):
    _inherit = "hr.department"
    _description = u"部门"
    _order = "name"

    ding_id = fields.Char(u'钉钉部门ID', help=u'部门id')
    ding_parentid = fields.Char(u'钉钉部门上级', default="1", help=u'父部门id，根部门为1')
    ding_createdeptgroup = fields.Boolean(u"创建部门群", default=False, help=u'是否同步创建一个关联此部门的企业群, true表示是, false表示不是')
    ding_autoadduser = fields.Boolean(u"部门新人自动加入该群,", default=False,
                                      help=u'当群已经创建后，是否有新人加入部门会自动加入该群, true表示是, false表示不是')
    ding_order = fields.Char(u'排序', default="1")
    ding_day = fields.Boolean("日报提醒", default=False)

    users = fields.One2many('ding.users', compute='_compute_users', string=u'员工',copy=False)

    @api.depends()
    def _compute_users(self):
        for order in self:
            order.users = self.env['ding.users'].search([('ding_department', 'ilike', order.ding_id)])

    def action_department(self):
        """
        当前部门详细信息
        """
        for line in self:
            self._cr.execute("SELECT access_token FROM res_ding WHERE company_id = %s " % line.company_id.id)
            access_token = [r[0] for r in self._cr.fetchall()]

            if len(access_token) == 0:
                pass
                #:::执行生成token
            else:
                client_obj = Client(None, None, access_token[0])
                json = client_obj.department_get(self.ding_id)
                if json['errcode'] == 40014:
                    records = self.env['res.ding'].search([('company_id', '=', line.company_id.id)], limit=1)
                    records.action_gettoken()
                    line.action_department();
                else:
                    if json['errcode'] != 0:
                        raise ValidationError(json['errmsg'])

                parm = {
                    'ding_outerdept': json['outerDept'],
                    'name': json['name'],
                    'ding_userperimits': json['userPerimits'],
                    'ding_outerpermitusers': json['outerPermitUsers'],
                    'ding_deptperimits': json['deptPerimits'],
                    'ding_order': json['order'],
                    # 'ding_orgdeptowner': json['orgDeptOwner'],
                    'ding_depthiding': json['deptHiding'],
                    'ding_outerpermitdepts': json['outerPermitDepts'],
                    'ding_deptmanageruseridlist': json['deptManagerUseridList'],
                    'ding_createdeptgroup': json['createDeptGroup'],
                    'ding_autoaddUser': json['autoAddUser'],
                    'ding_id': json['id'],

                }
                line.write(parm)

    def action_department_user(self):
        """
        当前部门下员工
        """
        for line in self:
            self._cr.execute("SELECT access_token FROM res_ding WHERE company_id = %s " % line.company_id.id)
            access_token = [r[0] for r in self._cr.fetchall()]
            if len(access_token) == 0:
                pass
                #:::执行生成token
            else:
                client_obj = Client(None, None, access_token[0])
                json = client_obj.user_simplelist(line.ding_id)
                if json['errcode'] == 40014:
                    records = self.env['res.ding'].search([('company_id', '=', line.company_id.id)], limit=1)
                    records.action_gettoken()
                    line.action_department_user();
                else:
                    if json['errcode'] != 0:
                        raise ValidationError(json['errmsg'])

                for user in json['userlist']:
                    # records = self.env['ding.users'].search([('mobile', '=', user['']),('email', '=', user[''])])
                    records = self.env['ding.users'].search([('ding_userid', '=', user['userid'])])
                    ding_user = client_obj.user_get(user['userid'])

                    values = {
                        'ding_orderindepts': ding_user['orderInDepts'],
                        'ding_department': ding_user['department'],
                        'ding_unionid': ding_user['unionid'],
                        'ding_userid': ding_user['userid'],
                        'ding_issenior': ding_user['isSenior'],
                        'ding_isboss': ding_user['isBoss'],
                        # 'ding_orgemail': ding_user['orgEmail'],
                        'name': ding_user['name'],
                        'mobile': ding_user['mobile'],
                        'email': ding_user['email'],
                        # 'ding_tags': ding_user['tags'],
                        # 'ding_statecode': ding_user['stateCode'],
                        'ding_avatar': ding_user['avatar'],
                        'ding_jobnumber': ding_user['jobnumber'],
                        'ding_isleaderindepts': ding_user['isLeaderInDepts'],
                        # 'ding_roles': ding_user['roles'],
                        'ding_isadmin': ding_user['isAdmin'],
                        # 'ding_openid': ding_user['openId'],
                        'ding_ishide': ding_user['isHide'],
                        'ding_department_ids': [(4, self.id)],
                    }

                    if ding_user.get('tel'):
                        values['ding_tel'] = ding_user['tel']

                    if ding_user.get('workPlace'):
                        values['ding_workplace'] = ding_user['workPlace']

                    if ding_user.get('remark'):
                        values['ding_remark'] = ding_user['remark']

                    if ding_user.get('position'):
                        values['ding_position'] = ding_user['position']

                    if records:
                        records.write(values)
                        self.login_conn(records)  # 创建登陆帐号
                    else:
                        print(values)
                        records = self.env['ding.users'].sudo().create(values)
                        self.login_conn(records) #创建登陆帐号



    def login_conn(self,ding):
        """
        用户自动关联
        :return:
        """
        if ding.ding_jobnumber=='':
            return True
        login = self.env['res.users'].sudo().search([('login', '=', ding.ding_jobnumber)],limit=1)
        if not login:
            default_user = self.env.ref('base.default_user', raise_if_not_found=False).copy()
            default = {}
            default['name'] = ding.name
            default['login'] = ding.ding_jobnumber
            default['active'] = True
            default_user.sudo().write(default)
        else:
            values = {
                'ding_id': ding.id,
                'name': ding.name,
            }
            ding.sudo().write(values)




    def action_ding_day(self):

        records = self.env['ding.message.template'].sudo().search([('model', '=', 'hr.department'), ('code', '=', 'vic_001')], limit=1)
        if records:
            template = Template(records.body_html)
            content = template.render(docs=self)
            for l in self.users:

                content = u'[等待审批] 申请人:%s\n向您!提交了一条%s等待审批信息,请即时审批!\n%s\n%s' % (self.env.user.name, '销售系统', content, '0000')
                self.env.user.d(l.user_id, content, None)
        else:
            self.env.user.notify_warning(message='未找到模板')


        return True